import terminalService, {
  type PageListReq,
} from "@/api/services/mes/terminalService";
import workshopService from "@/api/services/mes/workshopService";
import CustomTable from "@/components/grid/CustomTable";
import TableDictTag from "@/components/grid/TableDictTag";
import useDictionary from "@/hooks/system/useDictionary";
import { t } from "@/locales/i18n";
import {
  Button,
  Card,
  Cascader,
  Drawer,
  Form,
  Input,
  Select,
  Space,
  Spin,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import type { MesWorkshop } from "../workshop/entity";
import type { SopTerminal } from "./entity";

const { TextArea } = Input;

export default function SopTerminalPage() {
  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    name: undefined,
    workshopId: undefined,
    lineId: undefined,
    stationId: undefined,
    ip: undefined,
    status: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<SopTerminal[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingData, setEditingData] = useState<SopTerminal | null>(null);
  const [form] = Form.useForm();
  const [isView, setIsView] = useState(true);
  const [workshopTreeList, setWorkshopTreeList] = useState<MesWorkshop[]>([]);

  // 获取状态字典
  const statusOptions = useDictionary("sop_terminal_status");
  const reportingOptions = useDictionary("system_true_false");

  const columns: ColumnsType<SopTerminal> = [
    {
      title: "终端编码",
      width: 120,
      key: "code",
      dataIndex: "code",
    },
    {
      title: "终端名称",
      width: 120,
      key: "name",
      dataIndex: "name",
    },
    {
      title: "车间",
      width: 120,
      key: "workshopName",
      dataIndex: "workshopName",
    },
    {
      title: "产线",
      width: 120,
      key: "lineName",
      dataIndex: "lineName",
    },
    {
      title: "工位",
      width: 120,
      key: "stationName",
      dataIndex: "stationName",
    },
    {
      title: "终端IP",
      width: 120,
      key: "ip",
      dataIndex: "ip",
    },
    {
      title: "状态",
      width: 120,
      key: "status",
      dataIndex: "status",
      render: (_, record) => (
        <TableDictTag
          dictCode="sop_terminal_status"
          value={record.status ?? ""}
        />
      ),
    },
    {
      title: "备注",
      width: 120,
      key: "remark",
      dataIndex: "remark",
    },
    {
      title: "操作",
      fixed: "right",
      key: "operation",
      align: "center",
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            {t("common.view")}
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            {t("common.edit")}
          </Button>
        </Space>
      ),
    },
  ];

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    terminalService
      .pageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  //加载树形结构数据
  const fetchWorkshopTreeList = async () => {
    await workshopService
      .treeList(queryParams)
      .then((data) => {
        if (data) {
          setWorkshopTreeList(data);
        }
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchWorkshopTreeList();
  }, []);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  //触发编辑按钮
  const handleEdit = (sopTerminal: SopTerminal) => {
    setEditingData(sopTerminal);
    form.setFieldsValue({
      ...sopTerminal,
      workshopLineStation: [
        sopTerminal.workshopId,
        sopTerminal.lineId,
        sopTerminal.stationId,
      ],
    });
    setDrawerVisible(true);
    setIsView(false);
  };

  //触发视图按钮
  const handleView = (sopTerminal: SopTerminal) => {
    setEditingData(sopTerminal);
    form.setFieldsValue(sopTerminal);
    setIsView(true);
    setDrawerVisible(true);
  };

  //提交表单数据
  const handleSubmit = async (values: SopTerminal) => {
    try {
      setSubmitLoading(true);

      const [workshopId, lineId, stationId] = values.workshopLineStation || [];

      const data = {
        ...values,
        workshopId,
        lineId,
        stationId,
        id: editingData?.id,
      };
      if (editingData) {
        await terminalService.update(data);
        toast.success("更新显示终端 成功");
      } else {
        await terminalService.add(data);
        toast.success("创建显示终端 成功");
      }
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };
  //提交表单数据
  const handleNextAdd = async () => {
    try {
      setSubmitLoading(true);
      const values = form.getFieldsValue();

      const [workshopId, lineId, stationId] = values.workshopLineStation || [];
      const data = {
        ...values,
        workshopId,
        lineId,
        stationId,
        id: editingData?.id,
      };
      await terminalService.add(data);
      toast.success("创建显示终端 成功");

      setEditingData(null);
      form.resetFields();
      form.setFieldValue("status", "off_line");
      form.setFieldValue("reporting", "0");

      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingData(null);
    form.resetFields();
  };

  const handleAdd = () => {
    setEditingData(null);
    form.resetFields();
    form.setFieldValue("status", "off_line");
    form.setFieldValue("reporting", "0");
    setDrawerVisible(true);
    setIsView(false);
  };

  const handleDelete = async () => {
    try {
      setLoading(true);
      await terminalService.remove(selectedRowKeys);
      toast.success("删除显示终端 成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`删除失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const cascaderOptions = workshopTreeList.map((workshop) => ({
    value: workshop.id,
    label: workshop.name,
    children: (workshop.children || []).map((line) => ({
      value: line.id,
      label: line.name,
      children: (line.children || []).map((station) => ({
        value: station.id,
        label: station.name,
      })),
    })),
  }));

  return (
    <Spin spinning={submitLoading} tip="数据提交中..." size="large">
      <Card className="mb-4">
        <Form
          layout="inline"
          onFinish={(values) => {
            const [workshopId, lineId, stationId] =
              values.workshopLineStation || [];
            setQueryParams((prev) => ({
              ...prev,
              workshopId,
              lineId,
              stationId,
              page: 1,
            }));
          }}
        >
          <Form.Item name="name" label="终端名称">
            <Input placeholder="请输入终端名称" allowClear />
          </Form.Item>
          <Form.Item label="车间/产线/工位" name="workshopLineStation">
            <Cascader
              options={cascaderOptions}
              placeholder="请选择车间/产线/工位"
              allowClear
              changeOnSelect={false}
              style={{ width: 230 }}
            />
          </Form.Item>
          <Form.Item name="ip" label="终端IP">
            <Input placeholder="请输入终端IP" allowClear />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select options={statusOptions} style={{ width: 100 }} allowClear />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setQueryParams({ page: 1, pageSize: 10 });
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <div className="h-4" />
      <Card>
        <CustomTable
          loading={loading}
          columnsConfig={columns}
          dataSource={list}
          total={total}
          selectedRowKeys={selectedRowKeys}
          setSelectedRowKeys={setSelectedRowKeys}
          current={queryParams.page}
          pageSize={queryParams.pageSize}
          onRefresh={fetchPageList}
          onPageChange={handlePageChange}
          selectable
          toolbarButtons={
            <>
              <Button type="primary" onClick={handleAdd}>
                新增
              </Button>
              <Button
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={handleDelete}
              >
                删除
              </Button>
              {/* 你可以继续添加更多自定义按钮 */}
            </>
          }
        />
      </Card>
      <Drawer
        title={editingData ? "编辑显示终端 " : "新增显示终端 "}
        width={480}
        open={drawerVisible}
        onClose={handleDrawerClose}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={handleDrawerClose}>取消</Button>
            {!isView && (
              <>
                {!editingData && (
                  <Button type="primary" onClick={() => handleNextAdd()}>
                    继续添加
                  </Button>
                )}
                <Button type="primary" onClick={() => form.submit()}>
                  保存并关闭
                </Button>
              </>
            )}
          </div>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onFinish={handleSubmit}
          disabled={isView}
        >
          <Form.Item name="code" label="终端编码">
            <Input placeholder="请输入终端编码" allowClear />
          </Form.Item>

          <Form.Item
            name="name"
            label="终端名称"
            rules={[
              {
                required: true,
                message: "请填写终端名称",
              },
            ]}
          >
            <Input placeholder="请输入终端名称" allowClear />
          </Form.Item>

          <Form.Item
            label="车间/产线/工位"
            name="workshopLineStation"
            rules={[{ required: true, message: "请选择车间/产线/工位" }]}
          >
            <Cascader
              options={cascaderOptions}
              placeholder="请选择车间/产线/工位"
              allowClear
              changeOnSelect={false}
            />
          </Form.Item>

          <Form.Item
            name="ip"
            label="终端IP"
            rules={[
              {
                required: true,
                message: "请填写终端IP",
              },
            ]}
          >
            <Input placeholder="请输入终端IP" allowClear />
          </Form.Item>

          <Form.Item name="reporting" label="报工设备">
            <Select options={reportingOptions} allowClear />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[
              {
                required: true,
                message: "请填写状态",
              },
            ]}
          >
            <Select options={statusOptions} allowClear />
          </Form.Item>

          <Form.Item name="remark" label="备注">
            <TextArea />
          </Form.Item>
        </Form>
      </Drawer>
    </Spin>
  );
}
